package com.ssy.lingxi.member.merchant.serviceimpl.paas;

import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.model.vo.paas.PlatformProcessRuleVO;
import com.ssy.lingxi.member.merchant.entity.BasePlatformProcessDO;
import com.ssy.lingxi.member.merchant.entity.PlatformProcessRuleDO;
import com.ssy.lingxi.member.merchant.entity.RoleDO;
import com.ssy.lingxi.member.merchant.repository.BasePlatformProcessRepository;
import com.ssy.lingxi.member.merchant.repository.PlatformProcessRuleRepository;
import com.ssy.lingxi.member.merchant.repository.RoleRepository;
import com.ssy.lingxi.member.merchant.service.paas.IPaasPlatformProcessService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 基础平台会员审核流程（注册流程）相关接口实现类
 * @author 万宁
 * @version 2.0.0
 * @date 2021-11-09
 */
@Service
public class PaasPlatformProcessServiceImpl implements IPaasPlatformProcessService {
    @Resource
    private RoleRepository roleRepository;

    @Resource
    private BasePlatformProcessRepository basePlatformProcessRepository;

    @Resource
    private PlatformProcessRuleRepository platformProcessRuleRepository;

    /**
     * 新增或修改角色关联的平台会员审核流程
     *
     * @param platformProcessVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> insertOrUpdateBasePlatformProcess(PlatformProcessRuleVO platformProcessVO) {
        RoleDO roleDO = roleRepository.findById(platformProcessVO.getRoleId()).orElse(null);
        if(roleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        BasePlatformProcessDO basePlatformProcess = basePlatformProcessRepository.findFirstByProcessKey(platformProcessVO.getProcessKey());
        if(basePlatformProcess == null) {
            return Wrapper.fail(ResponseCode.MC_MS_BASE_PLATFORM_PROCESS_DOES_NOT_EXIST);
        }

        PlatformProcessRuleDO processRule = platformProcessRuleRepository.findFirstByRoleId(platformProcessVO.getRoleId());
        if(processRule == null) {
            processRule = new PlatformProcessRuleDO();
            processRule.setRoleId(platformProcessVO.getRoleId());
        }

        processRule.setProcessKey(basePlatformProcess.getProcessKey());
        processRule.setEmptyProcess(basePlatformProcess.getEmptyProcess());
        platformProcessRuleRepository.saveAndFlush(processRule);
        return Wrapper.success();
    }
}
